
package cn.cloud.all.security.oauth2.client.discovery;

import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;

public class ProviderDiscoveryClient {
    private static final String PROVIDER_END_PATH = "/.well-known/openid-configuration";
    private static final String ISSUER_ATTR_NAME = "issuer";
    private static final String AUTHORIZATION_ENDPOINT_ATTR_NAME = "authorization_endpoint";
    private static final String TOKEN_ENDPOINT_ATTR_NAME = "token_endpoint";
    private static final String USERINFO_ENDPOINT_ATTR_NAME = "userinfo_endpoint";
    private static final String JWK_SET_URI_ATTR_NAME = "jwks_uri";
    private final RestTemplate restTemplate = new RestTemplate();
    private final URI providerLocation;

    public ProviderDiscoveryClient(String providerLocationUri) {
        Assert.hasText(providerLocationUri, "providerLocationUri cannot be empty");
        try {
            this.providerLocation = UriComponentsBuilder.fromHttpUrl(providerLocationUri)
                    .path(PROVIDER_END_PATH)
                    .build()
                    .encode()
                    .toUri();
        } catch (Exception ex) {
            throw new IllegalArgumentException("Invalid URI for providerLocationUri: " + ex.getMessage(), ex);
        }
    }

    public ProviderConfiguration discover() {
        Map responseAttributes = this.restTemplate.getForObject(this.providerLocation, Map.class);

        ProviderConfiguration.Builder builder = new ProviderConfiguration.Builder();

        builder.issuer((String) responseAttributes.get(ISSUER_ATTR_NAME));
        builder.authorizationEndpoint((String) responseAttributes.get(AUTHORIZATION_ENDPOINT_ATTR_NAME));
        if (responseAttributes.containsKey(TOKEN_ENDPOINT_ATTR_NAME)) {
            builder.tokenEndpoint((String) responseAttributes.get(TOKEN_ENDPOINT_ATTR_NAME));
        }
        if (responseAttributes.containsKey(USERINFO_ENDPOINT_ATTR_NAME)) {
            builder.userInfoEndpoint((String) responseAttributes.get(USERINFO_ENDPOINT_ATTR_NAME));
        }
        if (responseAttributes.containsKey(JWK_SET_URI_ATTR_NAME)) {
            builder.jwkSetUri((String) responseAttributes.get(JWK_SET_URI_ATTR_NAME));
        }

        return builder.build();
    }
}